<template>
  <div class="admin-task-page">
    <!-- 顶部导航和搜索 -->
    <div class="admin-task-header">
      <div class="admin-task-title">
        <h2>系统任务管理</h2>
        <p class="desc">管理所有系统任务的创建、编辑、发布和状态控制</p>
      </div>
      <a-button type="primary" @click="openAddModal">
        <template #icon><i class="fa fa-plus"></i></template>
        新增系统任务
      </a-button>
    </div>
    <!-- 筛选区 -->
    <a-card class="mb-4">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="任务状态">
            <a-select v-model:value="filters.status" allow-clear>
              <a-select-option value="">全部状态</a-select-option>
              <a-select-option value="0">未发布</a-select-option>
              <a-select-option value="1">进行中</a-select-option>
              <a-select-option value="2">已结束</a-select-option>
              <a-select-option value="3">已暂停</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="任务类型">
            <a-select v-model:value="filters.taskType" allow-clear>
              <a-select-option value="">全部类型</a-select-option>
              <a-select-option value="0">系统任务</a-select-option>
              <a-select-option value="1">战队任务</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="难度等级">
            <a-select v-model:value="filters.difficultyLevel" allow-clear>
              <a-select-option value="">全部等级</a-select-option>
              <a-select-option value="1">1级 (简单)</a-select-option>
              <a-select-option value="2">2级 (基础)</a-select-option>
              <a-select-option value="3">3级 (进阶)</a-select-option>
              <a-select-option value="4">4级 (困难)</a-select-option>
              <a-select-option value="5">5级 (专家)</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="是否需要审核">
            <a-select v-model:value="filters.needReview" allow-clear>
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="0">无需审核</a-select-option>
              <a-select-option value="1">需要审核</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="flex justify-end mt-2">
        <a-button class="mr-2" @click="resetFilters"><i class="fa fa-refresh"></i> 重置</a-button>
        <a-button type="primary" @click="searchTasks"><i class="fa fa-filter"></i> 筛选</a-button>
      </div>
    </a-card>
    <!-- 任务列表 -->
    <a-card>
      <a-table :columns="columns" :data-source="taskList" :loading="loading" :pagination="paginationConfig.value" row-key="id" :scroll="{ x: 1100 }" size="small">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="statusColor(record.status)">{{ statusText(record.status) }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'taskType'">
            <a-tag :color="record.taskType === 0 ? 'blue' : 'purple'">{{ record.taskType === 0 ? '系统任务' : '战队任务' }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'difficultyLevel'">
            <a-tag :color="difficultyColor(record.difficultyLevel)"> {{ difficultyText(record.difficultyLevel) }} </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'rewardPoints'">
            <span>{{ record.rewardPoints }} 积分</span>
          </template>
          <template v-else-if="column.dataIndex === 'time'">
            <span>{{ record.time }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'username'">
            <span>{{ record.username || '-' }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'needReview'">
            <a-tag :color="record.needReview ? 'red' : 'green'">{{ record.needReview ? '需要审核' : '无需审核' }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'taskName'">
            <span>{{ record.taskName || '-' }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'taskDescription'">
            <span>{{ record.taskDescription || '-' }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-button type="link" @click="openEditModal(record)"><i class="fa fa-pencil"></i> 编辑</a-button>
              <a-popconfirm title="确定要删除该任务吗？" @confirm="deleteTask(record)">
                <a-button type="link" danger><i class="fa fa-trash"></i> 删除</a-button>
              </a-popconfirm>
              <a-button type="link" @click="viewTask(record)"><i class="fa fa-eye"></i> 详情</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 新增/编辑弹窗 -->
    <a-modal v-model:open="modalVisible" :title="modalType === 'add' ? '新增任务' : '编辑任务'" @ok="handleModalOk" :confirm-loading="modalLoading" @cancel="closeModal">
      <a-form :model="modalForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" layout="horizontal">
        <a-form-item label="任务名称" required>
          <a-input v-model:value="modalForm.taskName" placeholder="请输入任务名称" />
        </a-form-item>
        <a-form-item label="任务描述" required>
          <a-input v-model:value="modalForm.taskDescription" placeholder="请输入任务描述" />
        </a-form-item>
        <a-form-item label="任务类型" required>
          <a-select v-model:value="modalForm.taskType">
            <a-select-option :value="0">系统任务</a-select-option>
            <a-select-option :value="1">战队任务</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="难度等级" required>
          <a-select v-model:value="modalForm.difficultyLevel">
            <a-select-option :value="1">1级 (简单)</a-select-option>
            <a-select-option :value="2">2级 (基础)</a-select-option>
            <a-select-option :value="3">3级 (进阶)</a-select-option>
            <a-select-option :value="4">4级 (困难)</a-select-option>
            <a-select-option :value="5">5级 (专家)</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="奖励积分" required>
          <a-input-number v-model:value="modalForm.rewardPoints" :min="0" style="width: 100%" />
        </a-form-item>
        <a-form-item label="是否审核" required>
          <a-select v-model:value="modalForm.needReview">
            <a-select-option :value="0">无需审核</a-select-option>
            <a-select-option :value="1">需要审核</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="时间范围">
          <a-range-picker v-model:value="modalForm.timeRange" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="状态" required>
          <a-select v-model:value="modalForm.status">
            <a-select-option :value="0">未发布</a-select-option>
            <a-select-option :value="1">进行中</a-select-option>
            <a-select-option :value="2">已结束</a-select-option>
            <a-select-option :value="3">已暂停</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否公开" required>
          <a-select v-model:value="modalForm.isPublic">
            <a-select-option :value="0">仅队内可见</a-select-option>
            <a-select-option :value="1">公开可见</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  list as fetchTaskList,
  add as addTaskApi,
  update as updateTaskApi,
  deleteUsingPost as deleteTaskApi,
  detail as detailTaskApi
} from '@/api/bizTaskController'

const loading = ref(false)
const taskList = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const paginationConfig = computed(() => ({
  current: page.value,
  pageSize: pageSize.value,
  total: total.value,
  showTotal(t) { return `共 ${t} 条` },
  showSizeChanger: true,
  onChange(p, ps) {
    page.value = p
    pageSize.value = ps
    getTaskList()
  }
}))

const filters = reactive({
  status: '',
  taskType: '',
  difficultyLevel: '',
  needReview: ''
})

const columns = [
  { title: '任务名称', dataIndex: 'taskName', key: 'taskName', width: 120, ellipsis: true },
  { title: '任务描述', dataIndex: 'taskDescription', key: 'taskDescription', width: 220, ellipsis: true },
  { title: '任务类型', dataIndex: 'taskType', key: 'taskType', width: 90 },
  { title: '难度等级', dataIndex: 'difficultyLevel', key: 'difficultyLevel', width: 100 },
  { title: '奖励积分', dataIndex: 'rewardPoints', key: 'rewardPoints', width: 90 },
  { title: '时间范围', dataIndex: 'time', key: 'time', width: 180, ellipsis: true },
  { title: '任务创建人', dataIndex: 'username', key: 'username', width: 90, align: 'center' },
  { title: '是否审核', dataIndex: 'needReview', key: 'needReview', width: 90 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 90 },
  { title: '操作', dataIndex: 'action', key: 'action', width: 120, align: 'center', fixed: 'right' }
]

const getTaskList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: page.value,
      size: pageSize.value,
    }
    if (filters.status !== '') params.status = filters.status
    if (filters.taskType !== '') params.taskType = filters.taskType
    if (filters.difficultyLevel !== '') params.difficultyLevel = filters.difficultyLevel
    if (filters.needReview !== '') params.needReview = filters.needReview

    const res = await fetchTaskList(params)
    console.log('res', res.data)
    if (res.data.code === 0 && res.data.data) {
      console.log('res.data', res.data)
      taskList.value = res.data.data.list.map((item: any) => ({
        ...item,
        time: (item.startTime && item.endTime)
          ? `${dayjs(item.startTime).format('YYYY-MM-DD HH:mm:ss')} ~ ${dayjs(item.endTime).format('YYYY-MM-DD HH:mm:ss')}`
          : '长期有效'
      }))
      total.value = res.data.total
    } else {
      taskList.value = []
      total.value = 0
    }
    console.log('taskList', taskList.value)
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.status = ''
  filters.taskType = ''
  filters.difficultyLevel = ''
  filters.needReview = ''
  getTaskList()
}
const searchTasks = () => {
  page.value = 1
  getTaskList()
}

// 状态、难度等辅助
const statusText = (status) => {
  const arr = ['未发布', '进行中', '已结束', '已暂停']
  return arr[status] !== undefined ? arr[status] : '未知'
}
const statusColor = (status) => {
  const arr = ['default', 'success', 'error', 'warning']
  return arr[status] !== undefined ? arr[status] : 'default'
}
const difficultyText = (level) => {
  const arr = ['1级 (简单)', '2级 (基础)', '3级 (进阶)', '4级 (困难)', '5级 (专家)']
  return arr[level > 0 ? level - 1 : 0] ?? '未知'
}
const difficultyColor = (level) => {
  const arr = ['green', 'blue', 'orange', 'red', 'purple']
  return arr[level > 0 ? level - 1 : 0] ?? 'default'
}

// 弹窗表单
const modalVisible = ref(false)
const modalType = ref<'add'|'edit'>('add')
const modalLoading = ref(false)
const modalForm = reactive<any>({
  id: undefined,
  taskName: '',
  taskDescription: '',
  taskType: 0,
  difficultyLevel: 1,
  rewardPoints: 0,
  needReview: 0,
  timeRange: [],
  status: 0,
  isPublic: 0
})

const openAddModal = () => {
  modalType.value = 'add'
  Object.assign(modalForm, {
    id: undefined,
    taskName: '',
    taskDescription: '',
    taskType: 0,
    difficultyLevel: 1,
    rewardPoints: 0,
    needReview: 0,
    timeRange: [],
    status: 0,
    isPublic: 0
  })
  modalVisible.value = true
}
const openEditModal = async (record: any) => {
  modalType.value = 'edit'
  modalLoading.value = true
  try {
    const res = await detailTaskApi({ id: record.id })
    console.log('res', res.data) 
    if (res.data.code === 0 && res.data.data) {
      Object.assign(modalForm, {
        ...res.data.data,
        timeRange: res.data.startTime && res.data.endTime ? [dayjs(res.data.startTime), dayjs(res.data.endTime)] : []
      })
      modalVisible.value = true
    } else {
      message.error('获取任务详情失败')
    }
  } finally {
    modalLoading.value = false
  }
}
const closeModal = () => {
  modalVisible.value = false
}
const handleModalOk = async () => {
  modalLoading.value = true
  try {
    const submitData: any = {
      ...modalForm,
      startTime: modalForm.timeRange && modalForm.timeRange.length > 0 ? modalForm.timeRange[0].format('YYYY-MM-DD HH:mm:ss') : null,
      endTime: modalForm.timeRange && modalForm.timeRange.length > 0 ? modalForm.timeRange[1].format('YYYY-MM-DD HH:mm:ss') : null
    }
    // 新增或编辑时赋值creatorId
    if (currentUserId.value) {
      submitData.creatorId = currentUserId.value
    }
    if (modalType.value === 'add') {
      const res = await addTaskApi(submitData)
      if (res.data.code === 0) {
        message.success('新增成功')
        modalVisible.value = false
        getTaskList()
      } else {
        message.error(res.data.msg || '新增失败')
      }
    } else {
      const res = await updateTaskApi(submitData)
      if (res.data.code === 0) {
        message.success('编辑成功')
        modalVisible.value = false
        getTaskList()
      } else {
        message.error(res.data.msg || '编辑失败')
      }
    }
  } finally {
    modalLoading.value = false
    //获取所有数据刷新页面
    getTaskList()
  }
}
const deleteTask = async (record: any) => {
  loading.value = true
  try {
    const res = await deleteTaskApi({ id: record.id })
    if (res.code === 0) {
      message.success('删除成功')
      getTaskList()
    } else {
      message.error(res.msg || '删除失败')
    }
  } finally {
    loading.value = false
  }
}
const viewTask = (record: any) => {
  message.info(`任务ID: ${record.id}\n任务名称: ${record.taskName}`)
}

const currentUserId = ref<number | null>(null)
onMounted(() => {
  getTaskList()
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      currentUserId.value = userInfo.userId
    } catch (e) {
      currentUserId.value = null
    }
  }
})
</script>

<style scoped>
.admin-task-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 12px 4px;
}
.admin-task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.admin-task-title h2 {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 4px;
}
.admin-task-title .desc {
  color: #888;
  font-size: 15px;
}
.mb-4 {
  margin-bottom: 10px;
}
.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(60,141,188,0.04);
  padding: 12px;
  margin-bottom: 12px;
}
/* 表格字体和行高优化 */
.ant-table-wrapper .ant-table {
  font-size: 13px;
}
.ant-table-wrapper .ant-table-tbody > tr > td {
  padding: 8px 8px;
  line-height: 1.7;
}
.ant-table-wrapper .ant-table-thead > tr > th {
  padding: 8px 8px;
}
</style> 